package com.cg.asm.core.config.security;

import com.cg.asm.core.service.user.impl.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // 用户登录
    private UserInfoService userInfoService;
    // 自定义密码验证规则
    private CustomPasswordEncoder customPasswordEncoder;
    // 自定义权限拦截
    private UrlFilterInvocationSecurityMetadataSource urlFilterInvocationSecurityMetadataSource;
    // 决策管理器
    private UrlAccessDecisionManager urlAccessDecisionManager;
    // 登录失败结果处理
    private ResultAuthenticationFailureHandler resultAuthenticationFailureHandler;
    // 登录成功结果处理
    private ResultAuthenticationSuccessHandler resultAuthenticationSuccessHandler;
    // 授权失败结果处理
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;
    // 会话过期结果处理
    private RedirectInvalidSessionStrategy redirectInvalidSessionStrategy;
    // 失效回话（此帐户已在其他地方登录）结果处理
    private ResultSessionInformationExpiredStrategy resultSessionInformationExpiredStrategy;
    // 总控平台配置信息
    @Value("${asm.config.maximumSessions}")
    private Integer maximumSessions;

    @Autowired
    public WebSecurityConfig(UrlFilterInvocationSecurityMetadataSource urlFilterInvocationSecurityMetadataSource,
                             UrlAccessDecisionManager urlAccessDecisionManager,
                             ResultAuthenticationFailureHandler resultAuthenticationFailureHandler,
                             ResultAuthenticationSuccessHandler resultAuthenticationSuccessHandler,
                             AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler,
                             RedirectInvalidSessionStrategy redirectInvalidSessionStrategy,
                             ResultSessionInformationExpiredStrategy resultSessionInformationExpiredStrategy,
                             UserInfoService userInfoService,
                             CustomPasswordEncoder customPasswordEncoder) {
        this.urlFilterInvocationSecurityMetadataSource = urlFilterInvocationSecurityMetadataSource;
        this.urlAccessDecisionManager = urlAccessDecisionManager;
        this.resultAuthenticationFailureHandler = resultAuthenticationFailureHandler;
        this.resultAuthenticationSuccessHandler = resultAuthenticationSuccessHandler;
        this.authenticationAccessDeniedHandler = authenticationAccessDeniedHandler;
        this.redirectInvalidSessionStrategy = redirectInvalidSessionStrategy;
        this.resultSessionInformationExpiredStrategy = resultSessionInformationExpiredStrategy;
        this.userInfoService = userInfoService;
        this.customPasswordEncoder = customPasswordEncoder;
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setHideUserNotFoundExceptions(false);
        provider.setUserDetailsService(userInfoService);
        provider.setPasswordEncoder(customPasswordEncoder);
        return provider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/login/loginOutSuccess","/auth/session/**","/swagger-ui.html","/webjars/**","/v2/api-docs/**","/swagger-resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint())
                .and()
                .csrf().disable()
                .authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(urlFilterInvocationSecurityMetadataSource);
                        o.setAccessDecisionManager(urlAccessDecisionManager);
                        return o;
                    }
                }).and()
                .formLogin().loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").permitAll()
                .failureHandler(resultAuthenticationFailureHandler).successHandler(resultAuthenticationSuccessHandler).and()
                .logout().addLogoutHandler(new CustomLogoutHandler()).logoutSuccessHandler(new CustomLogoutSuccessHandler())
                .permitAll().and().csrf().disable().exceptionHandling()
                .accessDeniedHandler(authenticationAccessDeniedHandler)
                .and()
                .sessionManagement().invalidSessionStrategy(redirectInvalidSessionStrategy)
                .maximumSessions(maximumSessions)
                .expiredSessionStrategy(resultSessionInformationExpiredStrategy)
                .maxSessionsPreventsLogin(false).sessionRegistry(sessionRegistry());
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
}
